package com.dlc.shop.seckill.api.listener;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dlc.shop.bean.event.CheckSecKillOrderEvent;
import com.dlc.shop.bean.model.Order;
import com.dlc.shop.bean.model.OrderItem;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.seckill.common.model.Seckill;
import com.dlc.shop.seckill.common.service.SeckillService;
import com.dlc.shop.service.OrderItemService;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 支付时校验订单过期事件
 * @author lhd
 */
@Component("checkSecKillOrderListener")
@AllArgsConstructor
public class CheckSecKillOrderListener {


    private final OrderItemService orderItemService;
    private final SeckillService seckillService;

    @EventListener(CheckSecKillOrderEvent.class)
    public void checkSecKillOrderHandle(CheckSecKillOrderEvent event) {
        Order order = event.getOrder();
        OrderItem orderItem = orderItemService.getOne(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderNumber, order.getOrderNumber()));
        Seckill seckill = seckillService.getSeckillById(orderItem.getActivityId());
        // 订单创建时间经过秒杀限定分钟，如果为true则早于当前时间表示过期，抛出异常
//        if(!DateUtil.isExpired(seckillOrder.getCreateTime(), DateField.MINUTE, seckill.getMaxCancelTime(), new Date())){
         boolean isExpired = !DateUtil.offsetMinute(order.getCreateTime(),seckill.getMaxCancelTime()).after(new Date());
        if(isExpired){
            // 秒杀订单已经过期，无法进行支付
            throw new YamiShopBindException("yami.order.expired");
        }
    }

}
